package com.example.lets;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.bmob.BTPFileResponse;
import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.DownloadListener;
import com.bmob.btp.callback.UploadListener;


import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;

import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class InitiateEventActivity extends Activity {

	private String yearSelected;
	private Spinner spYear;
	private TextView tvYear;
	private TextView tvMonth;
	private Spinner spMonth;
	private String monthSelected;
	private Spinner spDay;
	private Spinner spHour;
	private  Spinner spMinutes;

	private SelectPicPopupWindow selWindow;
	private Uri photoUri = null;
	private String fileName = null;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_initiate_event);

		final Intent in = getIntent();
		String title = null;
		String description = null;
		String type = null;
		String picFileName = null;
		String actiTime = null;
		String actiPlace = null;
		String sponsorId = null;
		String baseAddress = null;
		String  detailAddress = null;
		String actiId = null;

		if(in.hasExtra("sponsorId")){
			title = in.getStringExtra("title");
			description = in.getStringExtra("description");
			type = in.getStringExtra("type");
			picFileName = in.getStringExtra("picFileName");
			actiTime = in.getStringExtra("time");
			actiPlace = in.getStringExtra("place");
			sponsorId = in.getStringExtra("sponsorId");
			String[] address = actiPlace.split("\\n");
			baseAddress = address[0];
			detailAddress = address[1];
			actiId = in.getStringExtra("actiId");
		}

		//这一坨是为了给修改活动信息的时候给地址赋初值
		TextView baseAddressTv = (TextView) this.findViewById(R.id.baseAddress);
		if(baseAddress != null)
			baseAddressTv.setText(baseAddress);

		EditText detailAddressTv = (EditText) this.findViewById(R.id.detailAddress);
		if(detailAddress != null)
			detailAddressTv.setText(detailAddress);

		TextView headTitle =(TextView) this.findViewById(R.id.initiate_event_title);
		if(sponsorId != null)
			headTitle.setText("修改活动信息");





		Button back = (Button) this.findViewById(R.id.initiate_event_back);
		back.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(InitiateEventActivity.this, HomeActivity.class);
				startActivity(intent);
				InitiateEventActivity.this.finish();
			}
		});


		final CheckBox sport = (CheckBox) InitiateEventActivity.this.findViewById(R.id.initiate_event_type_sport);
		final CheckBox food = (CheckBox) InitiateEventActivity.this.findViewById(R.id.initiate_event_type_food);
		final CheckBox tour = (CheckBox) InitiateEventActivity.this.findViewById(R.id.initiate_event_type_tour);
		final CheckBox study = (CheckBox) InitiateEventActivity.this.findViewById(R.id.initiate_event_type_study);
		final CheckBox game = (CheckBox) InitiateEventActivity.this.findViewById(R.id.initiate_event_type_game);
		final CheckBox movie = (CheckBox) InitiateEventActivity.this.findViewById(R.id.initiate_event_type_movie);

		sport.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				food.setChecked(false);
				tour.setChecked(false);
				study.setChecked(false);
				game.setChecked(false);
				movie.setChecked(false);

			}
		});

		food.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				sport.setChecked(false);
				tour.setChecked(false);
				study.setChecked(false);
				game.setChecked(false);
				movie.setChecked(false);

			}
		});

		tour.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				food.setChecked(false);
				sport.setChecked(false);
				study.setChecked(false);
				game.setChecked(false);
				movie.setChecked(false);

			}
		});

		study.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				food.setChecked(false);
				tour.setChecked(false);
				sport.setChecked(false);
				game.setChecked(false);
				movie.setChecked(false);

			}
		});

		game.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				food.setChecked(false);
				tour.setChecked(false);
				study.setChecked(false);
				sport.setChecked(false);
				movie.setChecked(false);

			}
		});

		movie.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				food.setChecked(false);
				tour.setChecked(false);
				study.setChecked(false);
				game.setChecked(false);
				sport.setChecked(false);

			}
		});


		if(type != null){//这一坨是为了在修改活动信息的时候给type赋初值
			if(type.equals("tour"))
				tour.setChecked(true);
			else if(type.equals("game"))
				game.setChecked(true);
			else if(type.equals("sport"))
				sport.setChecked(true);
			else if(type.equals("study"))
				study.setChecked(true);
			else if(type.equals("food"))
				food.setChecked(true);
			else
				movie.setChecked(true);
		}

		spYear = (Spinner) findViewById(R.id.initiate_event_time_year);
		spMonth = (Spinner) findViewById(R.id.initiate_event_time_month);
		spDay = (Spinner) findViewById(R.id.initiate_event_time_day);
		spHour = (Spinner) findViewById(R.id.initiate_event_time_hour);
		spMinutes = (Spinner) findViewById(R.id.initiate_event_time_minute);


		final String[] year = {"2015", "2016"};
		final String[] month = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};

		final String[] dayFebRun = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18",
				"19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29"};
		final String[] dayFebNotRun = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18",
				"19", "20", "21", "22", "23", "24", "25", "26", "27", "28"};
		final String[] daySmallMonth = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18",
				"19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"};
		final String[] dayBigMonth = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18",
				"19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};

		final String[] hour = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18",
				"19", "20", "21", "22", "23", "24"};
		final String[] minutes = {"30", "00"};

		final SpinnerAdapter adDayFebRun = new SpinnerAdapter(this, android.R.layout.simple_spinner_item, dayFebRun);
		adDayFebRun.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		final SpinnerAdapter adDayFebNotRun = new SpinnerAdapter(this, android.R.layout.simple_spinner_item, dayFebNotRun);
		adDayFebNotRun.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		final SpinnerAdapter adDaySmallMonth = new SpinnerAdapter(this, android.R.layout.simple_spinner_item, daySmallMonth);
		adDaySmallMonth.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		final SpinnerAdapter adDayBigMonth = new SpinnerAdapter(this, android.R.layout.simple_spinner_item, dayBigMonth);
		adDayBigMonth.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		final SpinnerAdapter adYear = new SpinnerAdapter(this, android.R.layout.simple_spinner_item, year);
		adYear.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spYear.setAdapter(adYear);

		SpinnerAdapter adMonth = new SpinnerAdapter(this, android.R.layout.simple_spinner_item, month);
		adMonth.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spMonth.setAdapter(adMonth);

		yearSelected = (String) spYear.getSelectedItem();
		monthSelected = (String) spMonth.getSelectedItem();
		spYear.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
									   int position, long id) {
				yearSelected = (String) spYear.getSelectedItem();
				if (yearSelected.equals("2016年") && monthSelected.equals("2月")) // ѡ�е���16�꣬�Ǹ�����
					spDay.setAdapter(adDayFebRun);
				else if (yearSelected.equals("2015年") && monthSelected.equals("2月"))
					spDay.setAdapter(adDayFebNotRun);

					// ѡ��һ�����£�ÿ����31��
				else if (monthSelected.equals("1月") || monthSelected.equals("3月") || monthSelected.equals("5月")
						|| monthSelected.equals("7月") || monthSelected.equals("8月")
						|| monthSelected.equals("10月") || monthSelected.equals("12月"))
					spDay.setAdapter(adDayBigMonth);
					// С�£�ÿ����30��
				else
					spDay.setAdapter(adDaySmallMonth);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
			}
		});

		spMonth.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
									   int position, long id) {
				monthSelected = (String) spMonth.getSelectedItem();
				yearSelected = (String) spYear.getSelectedItem();
				if (yearSelected.equals("2016年") && monthSelected.equals("2月")) // ѡ�е���16�꣬�Ǹ�����
					spDay.setAdapter(adDayFebRun);
				else if (yearSelected.equals("2015年") && monthSelected.equals("2月"))
					spDay.setAdapter(adDayFebNotRun);

					// ѡ��һ�����£�ÿ����31��
				else if (monthSelected.equals("1月") || monthSelected.equals("3月") || monthSelected.equals("5月")
						|| monthSelected.equals("7月") || monthSelected.equals("8月")
						|| monthSelected.equals("10月") || monthSelected.equals("12月"))
					spDay.setAdapter(adDayBigMonth);
					// С�£�ÿ����30��
				else
					spDay.setAdapter(adDaySmallMonth);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
			}

		});

		// ��hour����adapter
		SpinnerAdapter adHour = new SpinnerAdapter(this, android.R.layout.simple_spinner_item, hour);
		adHour.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spHour.setAdapter(adHour);

		// ��Minutes����adapter
		SpinnerAdapter adMinutes = new SpinnerAdapter(this, android.R.layout.simple_spinner_item, minutes);
		adMinutes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spMinutes.setAdapter(adMinutes);

		String yearPart = null;
		String monthPart = null;
		String dayPart = null;
		String hourPart = null;
		String minutePart = null;

		if(actiTime != null){
			String[] timeParts = actiTime.split("[- :]");
			yearPart = timeParts[0];
			monthPart = timeParts[1];
			dayPart = timeParts[2];
			hourPart = timeParts[3];
			minutePart = timeParts[4];

			int Y = Integer.parseInt(yearPart);
			int M = Integer.parseInt(monthPart);
			int D = Integer.parseInt(dayPart);
			int H = Integer.parseInt(hourPart);
			int Mi = Integer.parseInt(minutePart);

			spYear.setSelection(Y - 2015);
			spMonth.setSelection(M - 1);
			spDay.setSelection(D - 1);
			spHour.setSelection(H);
			if(Mi == 30)
				spMinutes.setSelection(0);
			else
				spMinutes.setSelection(1);
		}

		Button release = (Button) this.findViewById(R.id.initiate_event_release);
		if(sponsorId != null)
			release.setText("修改");

		release.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				String kind = "";

				if(sport.isChecked())
					kind = "sport";
				else if(food.isChecked())
					kind = "food";
				else if(study.isChecked())
					kind = "study";
				else if(tour.isChecked())
					kind = "tour";
				else if(movie.isChecked())
					kind = "movie";
				else if(game.isChecked())
					kind = "game";
				else{
					Toast.makeText(InitiateEventActivity.this, "请选择一个活动类别！", Toast.LENGTH_SHORT).show();
					return;
				}
				initiateActivity(kind);
			}

		});

		final ImageButton imgbtn = (ImageButton) this.findViewById(R.id.initiate_event_image);

		if(picFileName != null){ //这一坨是为了给在修改活动的时候设置现有图片
			final Context context = InitiateEventActivity.this;
			String cachePath = BmobPro.getInstance(context).getCacheDownloadDir() + "/" + picFileName;

			if ((new File(cachePath)).exists()) {  // 缓存存在直接加载
				Bitmap bm = BitmapFactory.decodeFile(cachePath);
				imgbtn.setImageBitmap(bm);
			}

			else { // 缓存不存在需要从远程下载
				BTPFileResponse response = BmobProFile.getInstance(context).download(picFileName, new DownloadListener() {
					@Override
					public void onSuccess(String fullPath) {
						// TODO Auto-generated method stub
						Bitmap bm = BitmapFactory.decodeFile(fullPath);
						imgbtn.setImageBitmap(bm);
					}

					@Override
					public void onProgress(String localPath, int percent) {
						// TODO Auto-generated method stub
						Log.i("bmob", "download-->onProgress :" + percent);
					}

					@Override
					public void onError(int statuscode, String errormsg) {
						// TODO Auto-generated method stub
						Log.i("bmob", "下载出错：" + statuscode + "--" + errormsg);
						Toast.makeText(context, "下载出错：" + statuscode + "--" + errormsg, Toast.LENGTH_SHORT).show();
					}
				});
			}
		}

		imgbtn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {

				// ʵ����SelectPicPopupWindow  
				selWindow = new SelectPicPopupWindow(InitiateEventActivity.this, new OnClickListener() {
					public void onClick(View v) {

						selWindow.dismiss();

						int id = v.getId();
						if (id == R.id.btn_take_photo) {
							SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
							String filename = "Lets_Head_" + timeStampFormat.format(new Date());
							ContentValues values = new ContentValues();
							values.put(Media.TITLE, filename);
							Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
							intent1.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
							startActivityForResult(intent1, 1);
						} else if (id == R.id.btn_pick_photo) {
							Intent intent2 = new Intent();
							intent2.setType("image/*");
							// ʹ��Intent.ACTION_GET_CONTENT���Action
							intent2.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(intent2, 2);
						} else {
							Log.i("bmob", "undefined button");
							Toast.makeText(InitiateEventActivity.this, "未定义的按钮！", Toast.LENGTH_SHORT).show();
						}
					}
				});

				// ��ʾ����
				selWindow.showAtLocation(InitiateEventActivity.this.findViewById(R.id.initiate_event_detail),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // ����layout��PopupWindow����ʾ��λ��
			}
		});

		EditText name = (EditText) InitiateEventActivity.this.findViewById(R.id.initiate_event_topic);
		if(title != null)
			name.setText(title);

		EditText detail = (EditText)InitiateEventActivity.this.findViewById(R.id.initiate_event_detail);
		if(description != null)
			detail.setText(description);

		TextView chooseAddress = (TextView) this.findViewById(R.id.baseAddress);
		chooseAddress.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(InitiateEventActivity.this, BaiduMapActivity.class);
				startActivityForResult(intent, 4);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.initiate_event, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressWarnings("deprecation")
	private void initiateActivity(String kind) {

		final User curUser = BmobUser.getCurrentUser(this, User.class);
		String sponsorId = curUser.getObjectId();
		String sponsorName = curUser.getNickname();

		String name = ((EditText) InitiateEventActivity.this.findViewById(R.id.initiate_event_topic)).getText().toString();
		String baseAddress = ((TextView) findViewById(R.id.baseAddress)).getText().toString();
		String detailAddress = ((EditText) findViewById(R.id.detailAddress)).getText().toString();
		String description = ((EditText)InitiateEventActivity.this.findViewById(R.id.initiate_event_detail)).getText().toString();

		String minute = ((Spinner) InitiateEventActivity.this.findViewById(R.id.initiate_event_time_minute)).getSelectedItem().toString();
		String hour = ((Spinner) InitiateEventActivity.this.findViewById(R.id.initiate_event_time_hour)).getSelectedItem().toString();
		String month = ((Spinner) InitiateEventActivity.this.findViewById(R.id.initiate_event_time_month)).getSelectedItem().toString();
		String day = ((Spinner) InitiateEventActivity.this.findViewById(R.id.initiate_event_time_day)).getSelectedItem().toString();
		String year = ((Spinner) InitiateEventActivity.this.findViewById(R.id.initiate_event_time_year)).getSelectedItem().toString();

		if (fileName == null || fileName.equals("")) {
			Log.i("bmob", "ͷ�񲻴���");
			Toast.makeText(InitiateEventActivity.this, "请为活动上传一张图片把", Toast.LENGTH_SHORT).show();
			return;
		}
		if (name == null || name.equals("")) {
			Toast.makeText(InitiateEventActivity.this, "请为活动起一个名字把", Toast.LENGTH_SHORT).show();
			return;
		}

		if (baseAddress == null || baseAddress.equals("点击选取活动地址")){
			Toast.makeText(InitiateEventActivity.this, "请输入活动的地点", Toast.LENGTH_SHORT).show();
			return;
		}
		if (description == null || description.equals("")) {
			Toast.makeText(InitiateEventActivity.this, "请描述一下你的活动", Toast.LENGTH_SHORT).show();
			return;
		}

		Calendar cal = Calendar.getInstance();
		cal.set(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day),
				Integer.parseInt(hour), Integer.parseInt(minute));
		Date date = cal.getTime();

		Calendar curCal = Calendar.getInstance();
		Date curDate = curCal.getTime();

		if (curDate.after(date)) {
			Toast.makeText(InitiateEventActivity.this, "时间已过期", Toast.LENGTH_SHORT).show();
			return;
		}

		BmobDate bmobDate = new BmobDate(date);

		final File file = new File(fileName);
		if (!file.exists()) {
			Toast.makeText(this, "图片不存在", Toast.LENGTH_SHORT);
			return;
		}

		final UserActivity ac = new UserActivity();
		ac.setDescription(description);
		ac.setPlace(baseAddress + "\n" + detailAddress);
		ac.setType(kind);
		ac.setName(name);
		ac.setSponsorId(sponsorId);
		ac.setSponsorName(sponsorName);
		ac.setStartTime(bmobDate);
		ac.setPeopleNumber(1);

		BTPFileResponse response = BmobProFile.getInstance(this).upload(fileName, new UploadListener() {

			@Override
			public void onSuccess(String fileName, String url, BmobFile file) {
				Log.i("bmob", "�ļ��ϴ��ɹ���" + fileName + ",�ɷ��ʵ��ļ���ַ��" + file.getUrl());
				ac.setPhoto(file);
				ac.setPicFilename(fileName);
				ac.save(InitiateEventActivity.this, new SaveListener() {

					@Override
					public void onSuccess() {
						Toast.makeText(InitiateEventActivity.this, "活动创建成功", Toast.LENGTH_SHORT).show();
						Log.i("bmob", "活动创建成功");
						Involvement in = new Involvement();
						in.setActivityId(ac.getObjectId()); //need check

						in.setSponsorId(curUser.getObjectId());
						in.setUserId(curUser.getObjectId());
						in.save(InitiateEventActivity.this, new SaveListener() {

							@Override
							public void onSuccess() {
								// TODO Auto-generated method stub

							}

							@Override
							public void onFailure(int code, String arg0) {
								// TODO Auto-generated method stub
							}
						});
						Intent intent = new Intent();
        				intent.setClass(InitiateEventActivity.this, HomeActivity.class);
        				startActivity(intent);
						InitiateEventActivity.this.finish();
					}

					@Override
					public void onFailure(int code, String arg0) {
						Toast.makeText(InitiateEventActivity.this, "活动创建失败", Toast.LENGTH_SHORT).show();
					}
				});
			}

			@Override
			public void onProgress(int progress) {
				Log.i("bmob", "onProgress :" + progress);
			}

			@Override
			public void onError(int statuscode, String errormsg) {
				Log.i("bmob", "BTPFILE失败" + errormsg);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case 1:
				if (resultCode == RESULT_OK) {
					Uri uri = null;
					if (data != null && data.getData() != null)
						uri = data.getData(); // �ü�ͼƬ
					else if (photoUri != null)
						uri = photoUri;
					else {
						Toast.makeText(this, "OnActivityResult出错，case1", Toast.LENGTH_SHORT);
					}
					cropPhoto(uri); // �ü�ͼƬ
				}
				break;

			case 2:
				if (data != null) {
					Uri uri = data.getData();
					cropPhoto(uri); // �ü�ͼƬ
					Log.e("uri", uri.toString());
				} else {
					Log.i("bmob", "ͼƬ�����ڣ�");
					Toast.makeText(this, "OnActivityResult出错，case2", Toast.LENGTH_SHORT);
				}
				break;

			case 3:
				if (data != null) {
					Bundle extras = data.getExtras();
					Bitmap head = extras.getParcelable("data");
					if (head != null) {
						setPicToView(head);
						ImageView imageView = (ImageView) findViewById(R.id.initiate_event_image);
						imageView.setImageBitmap(head);
					}
				}
				break;

			case 4:
				Bundle bundle = data.getExtras();
				if (bundle != null) {
					TextView baseAddressTv = (TextView) this.findViewById(R.id.baseAddress);
					EditText detailAddressTv = (EditText) this.findViewById(R.id.detailAddress);
					baseAddressTv.setText(bundle.getString("baseAddress"));
					detailAddressTv.setText(bundle.getString("detailAddress"));
				}
			default:
				break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	// ����ϵͳ�ü�
	public void cropPhoto(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		//intent.putExtra("aspectX", 16);
		//intent.putExtra("aspectY", 9);
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	private void setPicToView(Bitmap mBitmap) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
			return;
		}
		FileOutputStream b = null;
		String path = "/sdcard/Lets/myHead/";
		File file = new File(path);
		if (!file.exists())
			file.mkdirs(); // �����ļ���

		User curUser = BmobUser.getCurrentUser(this, User.class);
		fileName = path + curUser.getUsername() + "_head.jpg";
		try {
			b = new FileOutputStream(fileName);
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Log.i("bmob", e.getMessage());
		} finally {
			try { // �ر���
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onBackPressed() {
		Intent backIntent = new Intent(InitiateEventActivity.this, HomeActivity.class);
		startActivity(backIntent);
		finish();
		return;
	}
}

class SpinnerAdapter extends ArrayAdapter<String>{
	Context context;
	String [] items = new String[]{};

	public SpinnerAdapter(final Context context,final int textViewResourceId,final String[] s){
		super(context, textViewResourceId, s);
		this.items = s;
		this.context = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = LayoutInflater.from(context);
			convertView = inflater.inflate(
					android.R.layout.simple_spinner_item, parent, false);
		}

		// android.R.id.text1 is default text view in resource of the android.
		// android.R.layout.simple_spinner_item is default layout in resources of android.

		TextView tv = (TextView) convertView
				.findViewById(android.R.id.text1);
		tv.setText(items[position]);
		tv.setTextColor(Color.BLACK);
		tv.setTextSize(20);
		return convertView;
	}


}


